package win.bojack.redis_learning.boot.redis;

import redis.clients.jedis.Jedis;

import java.util.Random;

public class VerifyCode {

    public static void main(String[] args) {
        String phoneNum = "18108274520";
        // 得到发送次数的key和验证码的key
        String countKey = "VerifyCode_" + phoneNum + ":count";
        String codeKey  = "VerifyCode_" + phoneNum + ":code";
        Jedis jedis = new Jedis("127.0.0.1", 6379);

        // 获得发送次数
        String verifyCodeCount = jedis.get(countKey);

        // 如果发送次数为空，
        if (null == verifyCodeCount) {
            jedis.setex(countKey, 24 * 60 * 60, "1");
        } else if (Integer.parseInt(verifyCodeCount) <=2){
            jedis.incr(countKey);
        } else {
            throw new RuntimeException("已经获取了3次验证码，请明天再来吧");
        }

//        String code = genCode(4);
//        System.out.println(code);
//        jedis.setex(codeKey, 10 * 60, code);
        verifyCode("18108274520", "1977");
        jedis.close();
    }


    static void verifyCode(String phoneNum, String code) {
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        String codeKey  = "VerifyCode_" + phoneNum + ":code";
        String s = jedis.get(codeKey);
        if (null != s && s.equals(code)) {
            System.out.println("成功");
        } else {
            System.out.println("失败");
        }

        jedis.close();
    }

    // 生成指定位位数的验证码
    private static String genCode(int length) {
        if (length < 4 || length > 10) {
            throw new RuntimeException("难码长度太长或太短");
        }
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i =0;i<length;i++ ) {
            sb.append(random.nextInt(10));
        }

        return sb.toString();
    }
}
